import router from '@/router/index.js'
const modules = import.meta.glob('@/views/**/*.vue')

export const loadView = (view) => {
  let res
  for (const path in modules) {
    const dir = path.split('views/')[1].split('/')[1].split('.vue')[0]
    if (dir === view) {
      res = () => modules[path]()
    }
  }
  return res
}
export const filterRoute = (data, parent = 'layout') => {
  data.forEach((item) => {
    if (item.children?.length > 0) {
      delete item?.component
      filterRoute(item.children)
    } else {
      item.component = loadView(item.indexPath.split('/')[1])
      console.log('添加动态路由')
      router.addRoute(parent, {
        path: item.indexPath,
        name: item.indexPath.split('/')[1],
        component: item.component,
        meta: {
          title: item.title,
          icon: item.icon
        }
      })
    }
  })
  return data
}
export const renderRoute = (data, parent = 'home') => {
  for (let item of data) {
    if (item.children && item.children.length > 0) {
      router.addRoute(parent, {
        path: item.indexPath,
        name: item.indexPath,
        meta: {
          title: item.title,
          icon: item.icon
        }
      })
      renderRoute(item.children, item.indexPath)
    } else {
      router.addRoute(parent, {
        path: item.indexPath,
        name: item.indexPath.split('/')[1],
        component: () => import(`@/views/${item.indexPath.split('/')[1]}.vue`),
        meta: {
          title: item.title,
          icon: item.icon
        }
      })
    }
  }
}
